<template>
  <div class="chart-container">
    <div ref="chartRef" class="chart"></div>
    <div class="price-display">
      最新黄金价格：
      <span v-if="latestPrice !== null" class="price-value">{{ latestPrice.toFixed(2) }} 元/克</span>
      <span v-else class="loading">加载中...</span>
    </div>
  </div>
  <div class="price-indicators">
    <div class="indicator">
      <span>追仓位置：</span>
      <input 
        type="text" 
        v-model="editableChasePosition" 
        @keyup.enter="saveIndicators"
        class="indicator-input"
      >
      <span>元/克</span>
    </div>
    
    <div class="indicator">
      <span>止盈位置：</span>
      <input 
        type="text" 
        v-model="editableTakeProfit" 
        @keyup.enter="saveIndicators"
        class="indicator-input"
      >
      <span>元/克</span>
    </div>
    
    <div class="indicator">
      <span>止损位置：</span>
      <input 
        type="text" 
        v-model="editableStopLoss" 
        @keyup.enter="saveIndicators"
        class="indicator-input"
      >
      <span>元/克</span>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from "vue";
import * as echarts from "echarts";
import axios from "axios";

const chartRef = ref(null);
let chartInstance = null;
let intervalId = null;
const chasePosition = ref('765~766');
const takeProfit = ref('775+');
const stopLoss = ref('758');

const latestPrice = ref(null);
const previousPrice = ref(null);
const priceChange = ref(null);
const percentageChange = ref(null);

const initChart = (xLabels, yValues) => {
  if (!chartInstance) return;
  
  const option = {
    backgroundColor: '#ffffff',
    title: {
      text: '黄金实时价格折线图',
      left: 'center',
      textStyle: {
        color: '#333',
        fontSize: 18,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255,255,255,0.95)',
      borderWidth: 1,
      borderColor: '#eee',
      textStyle: {
        color: '#333'
      },
      formatter: (params) => {
        const x = params[0].axisValue;
        const y = params[0].data;
        return `<div style="font-weight:bold;margin-bottom:5px">${x}</div>
                <div>价格: <span style="color:#f4b400;font-weight:bold">${y.toFixed(2)} 元/克</span></div>`;
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: xLabels,
      axisLine: {
        lineStyle: {
          color: '#ccc'
        }
      },
      axisLabel: {
        color: '#666',
        rotate: 45,
        formatter: (val) => (val.length > 10 ? val.slice(11, 16) : val)
      },
      axisTick: {
        alignWithLabel: true
      }
    },
    yAxis: {
      type: 'value',
      name: '价格 (元/克)',
      nameTextStyle: {
        color: '#666',
        fontSize: 14
      },
      axisLine: {
        lineStyle: {
          color: '#ccc'
        }
      },
      axisLabel: {
        color: '#666',
        formatter: '{value}'
      },
      splitLine: {
        lineStyle: {
          type: 'dashed',
          color: '#eaeaea'
        }
      },
      min: (val) => Math.floor(val.min * 0.99 * 100) / 100,
      max: (val) => Math.ceil(val.max * 1.01 * 100) / 100
    },
    series: [
      {
        name: '金价',
        type: 'line',
        data: yValues,
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: {
          width: 4,
          color: '#f4b400',
          shadowColor: 'rgba(244, 180, 0, 0.3)',
          shadowBlur: 8,
          shadowOffsetY: 4
        },
        itemStyle: {
          color: '#f4b400',
          borderColor: '#fff',
          borderWidth: 2
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(244, 180, 0, 0.2)' },
            { offset: 1, color: 'rgba(244, 180, 0, 0.02)' }
          ])
        }
      }
    ]
  };

  chartInstance.setOption(option);
};

const fetchData = async () => {
  try {
    // 获取最新价格
    const res2 = await axios.get("http://localhost:8090/realtime-gold-price/getLatestGoldPrice");
    const newPrice = res2.data.price;
    
    // 计算价格变化
    if (latestPrice.value !== null) {
      previousPrice.value = latestPrice.value;
      priceChange.value = newPrice - latestPrice.value;
      percentageChange.value = (priceChange.value / latestPrice.value) * 100;
    }
    
    latestPrice.value = newPrice;
    
    // 获取图表数据
    const res = await axios.get(
      "http://localhost:8090/realtime-gold-price/getChartData"
    );
    const { xLabels, yValues } = res.data;
    initChart(xLabels, yValues);
  } catch (error) {
    console.error("获取数据失败：", error);
  }
};

onMounted(async () => {
  await nextTick();
  if (chartRef.value) {
    chartInstance = echarts.init(chartRef.value);
    fetchData();
    intervalId = setInterval(fetchData, 10 * 1000);
    window.addEventListener("resize", () => {
      chartInstance && chartInstance.resize();
    });
    fetchIndicators();
  } else {
    console.warn("图表容器未挂载");
  }
});

onBeforeUnmount(() => {
  if (intervalId) clearInterval(intervalId);
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
  window.removeEventListener("resize", () => {
    chartInstance && chartInstance.resize();
  });
});

// 可编辑的指标值
const editableChasePosition = ref('765~766');
const editableTakeProfit = ref('775+');
const editableStopLoss = ref('758');

// 保存指标到后端
const saveIndicators = async () => {
  try {
    // 调用保存接口
    await axios.post("http://localhost:8090/realtime-gold-price/updateCacheData", {
      chasePosition: editableChasePosition.value,
      takeProfit: editableTakeProfit.value,
      stopLoss: editableStopLoss.value
    });
    
    console.log("指标保存成功");
  } catch (error) {
    console.error("保存指标失败:", error);
  }
};

// 从后端获取指标值
const fetchIndicators = async () => {
  try {
    const response = await axios.get("http://localhost:8090/realtime-gold-price/getCacheData");
    const strategy = response.data;
    
    if (strategy) {
      editableChasePosition.value = strategy.chasePosition || '765~766';
      editableTakeProfit.value = strategy.takeProfit || '775+';
      editableStopLoss.value = strategy.stopLoss || '758';
    }
  } catch (error) {
    console.error("获取策略指标失败:", error);
  }
};

</script>

<style scoped>
.chart-container {
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 6px 30px rgba(0,0,0,0.08);
  padding: 20px;
  transition: all 0.3s ease;
}

.chart-container:hover {
  box-shadow: 0 8px 40px rgba(0,0,0,0.12);
}

.chart {
  width: 100%;
  height: 400px;
}

.price-display {
  margin-top: 20px;
  font-size: 18px;
  font-weight: bold;
  text-align: center;
  padding: 15px;
  background: #380707;
  border-radius: 8px;
}

.price-value {
  color: #f4b400;
  font-size: 1.2em;
  margin-left: 8px;
}

.loading {
  color: #888;
}

.price-change {
  margin-top: 8px;
  font-size: 14px;
  font-weight: normal;
}

.price-up {
  color: #e74c3c;
}

.price-down {
  color: #2ecc71;
}

.price-steady {
  color: #3498db;
}
</style>